<template>
  <view class="admin-feedback-page">
    <view class="page-header">
      <view class="header-left">
        <!-- <view class="back-btn" @click="navigateBack">
          <view class="icon icon-arrow-left" style="font-size: 20px;">‹</view>
          <text class="header-title">用户反馈</text>
        </view> -->
      </view>
      <view class="header-right">
          <picker 
            :range="statusOptions"
            mode="selector"
          @change="onStatusChange"
        >
          <view class="status-picker">
            <text>{{ statusOptions[selectedStatus] }}</text>
            <view class="icon icon-arrow-down" style="font-size: 16px; color: #999;">▼</view>
          </view>
        </picker>
      </view>
    </view>
    
    <!-- 反馈列表 -->
    <view class="feedback-list">
      <view 
        v-for="feedback in feedbacks" 
        :key="feedback._id" 
        class="feedback-item"
        @click="viewFeedbackDetail(feedback)"
      >
        <view class="feedback-header">
          <text class="user-name">用户 {{ feedback.userId?.substring(0, 8) || '匿名' }}</text>
          <view class="feedback-status" :class="`status-${feedback.status || 'pending'}`">
            {{ getStatusText(feedback.status) }}
          </view>
        </view>
        
        <text class="feedback-content">{{ feedback.content }}</text>
        
        <!-- 反馈图片 -->
        <view v-if="feedback.images && feedback.images.length > 0" class="feedback-images">
          <image 
            v-for="(image, index) in feedback.images.slice(0, 3)" 
            :key="index" 
            :src="image" 
            mode="aspectFill" 
            class="feedback-image"
          ></image>
          <view v-if="feedback.images.length > 3" class="more-images">
            +{{ feedback.images.length - 3 }}
          </view>
        </view>
        
        <!-- 联系方式 -->
        <text v-if="feedback.contact" class="contact-info">联系方式: {{ feedback.contact }}</text>
        
        <view class="feedback-footer">
          <text class="create-time">{{ formatTime(feedback.createTime) }}</text>
          <button 
            v-if="!feedback.status || feedback.status === 'pending'" 
            size="mini" 
            type="warn" 
            @click.stop="markAsProcessed(feedback._id)"
          >
            标记已处理
          </button>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMoreFeedbacks">
      <text v-if="!isLoading">点击加载更多</text>
      <text v-else>加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-if="feedbacks.length === 0 && !isLoading" class="empty-state">
      <view class="icon icon-chatbubble" style="font-size: 64px; color: #ccc;">💬</view>
      <text class="empty-text">暂无反馈</text>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-state">
      <uni-load-more :status="'loading'" />  
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onReady,onLoad } from '@dcloudio/uni-app';

// 状态管理
const feedbacks = ref([]);
const selectedStatus = ref(0); // 0: 全部, 1: 待处理, 2: 处理中, 3: 已解决
const statusOptions = ref(['全部', '待处理', '处理中', '已解决']);
const pageSize = 20;
const currentPage = ref(1);
const hasMore = ref(true);
const isLoading = ref(false);

// 生命周期
onLoad(() => {
  // 移除管理员权限校验
  loadFeedbacks();
});

// 管理员权限校验已移除

// 加载反馈数据
const loadFeedbacks = async (isLoadMore = false) => {
  if (isLoading.value) return;
  
  isLoading.value = true;
  
  try {
    const page = isLoadMore ? currentPage.value + 1 : 1;
    const statusMap = [null, 'pending', 'processing', 'resolved'];
    const status = statusMap[selectedStatus.value];
    
    // 使用新的云函数获取反馈列表
    const res = await uniCloud.callFunction({
      name: 'getFeedbacksList',
      data: {
        status,
        page,
        pageSize
      }
    });
    
    if (res && res.result && res.result.success) {
      const newFeedbacks = res.result.data || [];
      
      if (isLoadMore) {
        feedbacks.value = [...feedbacks.value, ...newFeedbacks];
      } else {
        feedbacks.value = newFeedbacks;
      }
      
      hasMore.value = newFeedbacks.length === pageSize;
      currentPage.value = page;
    }
  } catch (error) {
    console.error('加载反馈失败:', error);
    uni.showToast({ title: '加载失败，请稍后重试', icon: 'none' });
  } finally {
    isLoading.value = false;
  }
};


// 状态改变
const onStatusChange = (e) => {
  selectedStatus.value = e.detail.value;
  currentPage.value = 1;
  hasMore.value = true;
  loadFeedbacks();
};

// 加载更多
const loadMoreFeedbacks = () => {
  if (hasMore.value && !isLoading.value) {
    loadFeedbacks(true);
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待处理';
    case 'processing':
      return '处理中';
    case 'resolved':
      return '已解决';
    default:
      return '未知状态';
  }
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 查看反馈详情
const viewFeedbackDetail = (feedback) => {
  // 确保路径格式正确，使用标准格式并进行参数编码
  uni.navigateTo({
    url: `/pages/admin/feedback-detail?id=${feedback._id}`,
    fail: (err) => {
      console.error('导航失败:', err);
      uni.showToast({
        title: '页面加载失败',
        icon: 'none'
      });
    }
  });
};



// 标记为已处理
const markAsProcessed = async (feedbackId) => {
  try {
    const result = await uniCloud.callFunction({
      name: 'updateFeedback',
      data: {
        id: feedbackId,
        status: 'processing'
      }
    });
    
    if (result && result.result && result.result.success) {
      uni.showToast({ title: '标记成功' });
      // 更新本地数据
      const feedback = feedbacks.value.find(f => f._id === feedbackId);
      if (feedback) {
        feedback.status = 'processing';
      }
    } else {
      uni.showToast({ title: '标记失败', icon: 'none' });
    }
  } catch (error) {
    console.error('标记反馈状态失败:', error);
    uni.showToast({ title: '标记失败，请稍后重试', icon: 'none' });
  }
};

</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.admin-feedback-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .header-left {
      .back-btn {
        display: flex;
        align-items: center;
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-left: 4px;
        }
      }
    }
    
    .header-right {
      .status-picker {
        display: flex;
        align-items: center;
        padding: 6px 12px;
        background-color: #f5f5f5;
        border-radius: 16px;
        font-size: 14px;
        
        .icon {
          margin-left: 4px;
        }
      }
    }
  }
  
  .feedback-list {
    padding: 16px;
    
    .feedback-item {
      background-color: #fff;
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .feedback-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        
        .user-name {
          font-size: 14px;
          color: #666;
        }
        
        .feedback-status {
          padding: 2px 8px;
          border-radius: 12px;
          font-size: 12px;
          
          &.status-pending {
            background-color: #fff7e6;
            color: #fa8c16;
          }
          
          &.status-processed {
            background-color: #f6ffed;
            color: #52c41a;
          }
        }
      }
      
      .feedback-content {
        display: block;
        font-size: 14px;
        color: #333;
        line-height: 1.5;
        margin-bottom: 12px;
        word-break: break-all;
      }
      
      .feedback-images {
        display: flex;
        gap: 8px;
        margin-bottom: 12px;
        
        .feedback-image {
          width: 60px;
          height: 60px;
          border-radius: 4px;
        }
        
        .more-images {
          width: 60px;
          height: 60px;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 4px;
          font-size: 14px;
        }
      }
      
      .contact-info {
        display: block;
        font-size: 12px;
        color: #666;
        margin-bottom: 12px;
      }
      
      .feedback-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .create-time {
          font-size: 12px;
          color: #999;
        }
        
        button {
          font-size: 12px;
          height: 28px;
          line-height: 28px;
        }
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 16px;
    font-size: 14px;
    color: #666;
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 64px 0;
    
    .empty-text {
      font-size: 14px;
      color: #999;
      margin-top: 16px;
    }
  }
  
  .loading-state {
    padding: 24px 0;
    display: flex;
    justify-content: center;
  }
}
</style>